<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\MessageNotificationRead;
use app\Request;
use think\App;
use think\db\exception\DbException;
use think\response\Json;
use app\company\model\MessageNotification as MessageNotificationModel;

/**
 * @ControllerAnnotation(title="信息通知管理")
 */
class MessageNotification extends CompanyController
{
    private MessageNotificationRead $read;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MessageNotificationModel();
        $this->read = new MessageNotificationRead();
    }

    /**
     * @NodeAnnotation (title="查询列表")
     * @throws DbException
     */
    public function messageNotifications(Request $request): Json
    {
        $keyword = $this->request->get('keyword');
        $startTime = $this->request->get('start_time');
        $endTime = $this->request->get('end_time');
        $limit = $this->request->get('limit', 10);
        $typeId = $this->request->get('type_id');
        $isRead = $this->request->get('is_read');
        $userId = $this->uid;

        // 初始化查询条件
        $where = [['company_id', '=', $this->companyId]];
        if (!empty($keyword)) {
            $where[] = ['title', 'like', "%{$keyword}%"];
        }
        if ($typeId) {
            $type = \app\company\model\MessageNotificationType::find($typeId);
            if (!$type) {
                return $this->error('分类不存在');
            }
            $where[] = ['type_id', '=', $typeId];
        }

        $query = $this->model->where($where)
            ->hasWhere('reads', function ($query) use ($isRead, $userId) {
                $this->addReadCondition($query, $isRead, $userId);

            })->with(['reads' => function ($query) use ($isRead, $userId) {
                $this->addReadCondition($query, $isRead, $userId);
            },
            'type' => function ($query) {
                $query->field('id, name');
            }
        ])
            ->when($startTime && $endTime, function ($query) use ($startTime, $endTime) {
            $query->whereBetween('send_time', [$startTime, $endTime]);
        })->order('send_time', 'desc');

        $messageNotifications = $query->paginate($limit);

        return $this->success($messageNotifications);
    }

    /**
     * 条件过滤
     *
     * @param $query
     * @param $isRead
     * @param $userId
     * @return void
     */
    private function addReadCondition($query, $isRead, $userId): void
    {
        $query->where('user_id', $userId)->field('id, message_notification_id, is_read');
        if (!is_null($isRead)) {
            $query->where('is_read', $isRead);
        }
    }

    /**
     * 详情+记录
     * @param int $id
     * @return Json
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function messageNotification(int $id)
    {
        $user = $this->userInfo;
        $message = $this->model->with('type')->find($id);
        if (!$message) {
            return $this->error('该消息不存在');
        }
        $where = [
            'message_notification_id' => $id,
            'user_id' => $user['id'],
        ];
        $read = $this->read->where($where)->find();
        if ($read && $read->read_time == null) {
            $read->is_read = MessageNotificationRead::IS_READ;
            $read->read_time = time();
            $read->save();
        }

        return $this->success($message);
    }

    /**
     * 未读消息统计
     *
     * @return Json
     */
    public function unReadMessageCount()
    {
        $user = $this->userInfo;
        $count = $this->read->where([
            'user_id' => $user['id'],
            'is_read' => MessageNotificationRead::IS_NOT_READ,
        ])->count();

        return $this->success($count);
    }
}